<template>
    <div class="collect-root">
      <div class="grid-container">
        <!-- 光电传感器 (原 TeachingCollect.vue) -->
        <div class="collect-card sensor-card">
          <div class="header-section">
            <h2>光电传感器</h2>
            <img src="/src/assets/sensor.png" alt="Sensor" class="device-image" />
          </div>
          <div class="input-section">
            <div class="input-item-no-input">
              <span class="red-diamond">◆</span>
              <h3>灵敏度</h3>
            </div>
            <div class="input-group">
              <div class="group-title">调试方法:</div>
              <el-input
                v-model="inputValues['1-1'].question"
                type="textarea"
                :rows="1"
                placeholder="请输入调试方法..."
                class="group-input"
              />
            </div>
            <div class="input-group">
              <div class="group-title">注意事项:</div>
              <el-input
                v-model="inputValues['1-1'].answer"
                type="textarea"
                :rows="1"
                placeholder="请输入注意事项..."
                class="group-input"
              />
            </div>
          </div>
        </div>
  
        <!-- 传送带传输 (原 TeachingCollect3.vue) -->
        <div class="collect-card conveyor-card">
          <div class="header-section">
            <h2>传送带传输</h2>
            <img src="/src/assets/conveyor.png" alt="Conveyor" class="device-image" />
          </div>
          <div class="input-section">
            <div class="input-item-no-input">
              <span class="red-diamond">◆</span>
              <h3>变频器参数</h3>
            </div>
            <div class="input-group">
              <div class="group-title">调试方法:</div>
              <el-input
                v-model="inputValues['3-6'].question"
                type="textarea"
                :rows="1"
                placeholder="请输入调试方法..."
                class="group-input"
              />
            </div>
  
            <div class="input-group">
              <div class="group-title">注意事项:</div>
              <el-input
                v-model="inputValues['3-6'].answer"
                type="textarea"
                :rows="1"
                placeholder="请输入注意事项..."
                class="group-input"
              />
            </div>
          </div>
        </div>
  
        <!-- 视觉相机 (原 TeachingCollect2.vue) -->
        <div class="collect-card camera-card">
          <div class="header-section">
            <h2>视觉相机</h2>
            <img src="/src/assets/camera.png" alt="Camera" class="device-image" />
          </div>
          <div class="input-section">
            <div class="input-item-no-input">
              <span class="red-diamond">◆</span>
              <h3>分辨率与帧率</h3>
            </div>
            <div class="input-group">
              <div class="group-title">调试方法:</div>
              <el-input
                v-model="inputValues['2-2'].question"
                type="textarea"
                :rows="1"
                placeholder="请输入调试方法..."
                class="group-input"
              />
            </div>
            <div class="input-group">
              <div class="group-title">注意事项:</div>
              <el-input
                  v-model="inputValues['2-2'].answer"
                  type="textarea"
                  :rows="1"
                  placeholder="请输入注意事项..."
                  class="group-input"
              />
            </div>

            <div class="input-item-no-input">
              <span class="red-diamond">◆</span>
              <h3>曝光时间与增益</h3>
            </div>
            <div class="input-group">
              <div class="group-title">调试方法:</div>
              <el-input
                v-model="inputValues['2-3'].question"
                type="textarea"
                :rows="1"
                placeholder="请输入调试方法..."
                class="group-input"
              />
            </div>
            <div class="input-group">
              <div class="group-title">注意事项:</div>
              <el-input
                  v-model="inputValues['2-3'].answer"
                  type="textarea"
                  :rows="1"
                  placeholder="请输入注意事项..."
                  class="group-input"
              />
            </div>
  
            <div class="input-item-no-input">
              <span class="red-diamond">◆</span>
              <h3>白平衡</h3>
            </div>
            <div class="input-group">
              <div class="group-title">调试方法:</div>
              <el-input
                v-model="inputValues['2-4'].question"
                type="textarea"
                :rows="1"
                placeholder="请输入调试方法..."
                class="group-input"
              />
            </div>
            <div class="input-group">
              <div class="group-title">注意事项:</div>
              <el-input
                  v-model="inputValues['2-4'].answer"
                  type="textarea"
                  :rows="1"
                  placeholder="请输入注意事项..."
                  class="group-input"
              />
            </div>

            <div class="input-item-no-input">
              <span class="red-diamond">◆</span>
              <h3>焦距与对焦</h3>
            </div>
            <div class="input-group">
              <div class="group-title">调试方法:</div>
              <el-input
                v-model="inputValues['2-5'].question"
                type="textarea"
                :rows="1"
                placeholder="请输入调试方法..."
                class="group-input"
              />
            </div>
  
            <div class="input-group">
              <div class="group-title">注意事项:</div>
              <el-input
                  v-model="inputValues['2-5'].answer"
                  type="textarea"
                  :rows="1"
                  placeholder="请输入注意事项..."
                  class="group-input"
              />
            </div>

          </div>
        </div>
  
        <!-- 设备调试智慧画布 (中间图片) -->
<!--       <div class="middle-image-container">-->
<!--         &lt;!&ndash; <h2>设备调试智慧画布</h2> &ndash;&gt;-->
<!--         <img src="/src/assets/middle.png" alt="Middle" class="middle-image" />-->
<!--        </div>-->
  
        <!-- 推料气缸 (原 TeachingCollect4.vue) -->
        <div class="collect-card cylinder-card">
          <div class="header-section">
            <h2>推料气缸</h2>
            <img src="/src/assets/cylinder.png" alt="Cylinder" class="device-image" />
          </div>
          <div class="input-section">
            <div class="input-item-no-input">
              <span class="red-diamond">◆</span>
              <h3>气缸动作力度</h3>
            </div>
            <div class="input-group">
              <div class="group-title">调试方法:</div>
              <el-input
                v-model="inputValues['4-7'].question"
                type="textarea"
                :rows="1"
                placeholder="请输入调试方法..."
                class="group-input"
              />
            </div>
            <div class="input-group">
              <div class="group-title">注意事项:</div>
              <el-input
                  v-model="inputValues['4-7'].answer"
                  type="textarea"
                  :rows="1"
                  placeholder="请输入注意事项..."
                  class="group-input"
              />
            </div>

            <div class="input-item-no-input">
              <span class="red-diamond">◆</span>
              <h3>气缸动作速度</h3>
            </div>
            <div class="input-group">
              <div class="group-title">调试方法:</div>
              <el-input
                v-model="inputValues['4-8'].question"
                type="textarea"
                :rows="1"
                placeholder="请输入调试方法..."
                class="group-input"
              />
            </div>
            <div class="input-group">
              <div class="group-title">注意事项:</div>
              <el-input
                  v-model="inputValues['4-8'].answer"
                  type="textarea"
                  :rows="1"
                  placeholder="请输入注意事项..."
                  class="group-input"
              />
            </div>

            <div class="input-item-no-input">
              <span class="red-diamond">◆</span>
              <h3>磁性开关位置</h3>
            </div>
            <div class="input-group">
              <div class="group-title">调试方法:</div>
              <el-input
                v-model="inputValues['4-9'].question"
                type="textarea"
                :rows="1"
                placeholder="请输入调试方法..."
                class="group-input"
              />
            </div>
            <div class="input-group">
              <div class="group-title">注意事项:</div>
              <el-input
                  v-model="inputValues['4-9'].answer"
                  type="textarea"
                  :rows="1"
                  placeholder="请输入注意事项..."
                  class="group-input"
              />
            </div>

          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, reactive, watch } from 'vue'
  import { useRoute } from 'vue-router'
  import { updateQuestion as apiUpdateQuestion, updateTeachingAnswer as apiUpdateAnswer } from '../api'
  
  const route = useRoute()
  const userId = computed(() => Number(route.query.user_id) || 0)

  // 定义所有设备的配置，包括ID、名称、图片、背景颜色和参数列表
  const deviceConfigs = ref([
    {
      id: 1, // 光电传感器 (原 TeachingCollect.vue)
      name: '光电传感器',
      image: '/src/assets/sensor.png',
      parameters: [{ label: '灵敏度', type: 1 }] // deviceId: 1, type: 1
    },
    {
      id: 2, // 视觉相机 (原 TeachingCollect2.vue)
      name: '视觉相机',
      image: '/src/assets/camera.png',
      parameters: [
        { label: '分辨率与帧率', type: 2 }, // deviceId: 2, type: 2
        { label: '曝光时间与增益', type: 3 }, // deviceId: 2, type: 3
        { label: '白平衡', type: 4 }, // deviceId: 2, type: 4
        { label: '焦距与对焦', type: 5 }  // deviceId: 2, type: 5
      ]
    },
    {
      id: 3, // 传送带传输 (原 TeachingCollect3.vue)
      name: '传送带传输',
      image: '/src/assets/conveyor.png',
      parameters: [{ label: '变频器参数', type: 6 }] // deviceId: 3, type: 6
    },
    {
      id: 4, // 推料气缸 (原 TeachingCollect4.vue)
      name: '推料气缸',
      image: '/src/assets/cylinder.png',
      parameters: [
        { label: '气缸动作力度', type: 7 }, // deviceId: 4, type: 7
        { label: '气缸动作速度', type: 8 }, // deviceId: 4, type: 8
        { label: '磁性开关位置', type: 9 }  // deviceId: 4, type: 9
      ]
    }
  ])

  // 使用reactive对象来存储所有输入框的值
  // 键为`${deviceId}-${type}`，值为一个嵌套的reactive对象，其属性直接为字符串
  const inputValues = reactive({});

  // 初始化inputValues，确保每个设备参数的question和answer字段都有响应式字符串
  deviceConfigs.value.forEach(device => {
    device.parameters.forEach(param => {
      const key = `${device.id}-${param.type}`;
      inputValues[key] = reactive({
        question: '',
        answer: ''
      });
    });
  });

  const timers = new Map(); // 用于管理防抖定时器

  // 为所有输入字段添加 watch 效应，实现防抖和API调用
  deviceConfigs.value.forEach(device => {
    device.parameters.forEach(param => {
      const key = `${device.id}-${param.type}`; // 例如 '1-1', '2-2', '3-6', '4-7'

      // 监听 question 字段的变化
      watch(() => inputValues[key].question, (newValue, oldValue) => {
        if (newValue !== oldValue) {
          const fullKey = `${key}-question`;
          if (timers.has(fullKey)) {
            clearTimeout(timers.get(fullKey));
          }
          const timer = setTimeout(() => {
            // 确保所有参数都转换为 Number 类型，与后端匹配
            apiUpdateQuestion(userId.value, Number(device.id), Number(param.type), newValue)
              .catch(error => console.error(`Error updating question for ${fullKey}:`, error));
          }, 500); // 500ms 防抖
          timers.set(fullKey, timer);
        }
      });

      // 监听 answer 字段的变化
      watch(() => inputValues[key].answer, (newValue, oldValue) => {
        if (newValue !== oldValue) {
          const fullKey = `${key}-answer`;
          if (timers.has(fullKey)) {
            clearTimeout(timers.get(fullKey));
          }
          const timer = setTimeout(() => {
            // 确保所有参数都转换为 Number 类型，与后端匹配
            apiUpdateAnswer(userId.value, Number(device.id), Number(param.type), newValue)
              .catch(error => console.error(`Error updating answer for ${fullKey}:`, error));
          }, 500); // 500ms 防抖
          timers.set(fullKey, timer);
        }
      });
    });
  });

  </script>
  
  <style scoped>
  .collect-root {
    min-height: 100vh;
    display: flex;
    flex-direction: column; /* 改为垂直排列 */
    align-items: center;
    justify-content: flex-start; /* 从顶部开始排列 */
    background: linear-gradient(to bottom right, #f0f2f5, #e0e5ec); /* 柔和的渐变背景 */
    padding: 20px; /* 减少整体内边距 */
    box-sizing: border-box;
  }
  
  .grid-container {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, auto); /* 仍然使用auto，避免内容被裁剪 */
    gap: 20px; /* 减少网格间距 */
    max-width: 1200px; /* 进一步减少最大宽度 */
    width: 100%;
    position: relative;
    margin-top: 50px; /* 增加顶部间距，为中间图片腾出空间 */
  }
  
  .collect-card {
    background-color: #f0f2f5; /* 默认卡片背景色 */
    border-radius: 12px;
    padding: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .collect-card:hover {
    transform: translateY(-3px); /* 悬停时轻微上浮 */
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15); /* 悬停时阴影更深 */
  }
  
  /* 针对不同卡片设置背景颜色 - 保持柔和色调 */
  .sensor-card {
    background-color: #CCFFFF; /* 左上角 div 的背景色 */
    border: 1px solid #d4edda;
  }
  .conveyor-card {
    background-color: #99CCFF;
    border: 1px solid #d4e7f7;
  }
  .camera-card {
    background-color: #FFFF99;
    border: 1px solid #fae8d4;
  }
  .cylinder-card {
    background-color: #FF99FF;
    border: 1px solid #f7d4d4;
  }
  
  .header-section {
    display: flex;
    flex-direction: row; /* 改为水平排列 */
    align-items: center; /* 垂直居中对齐 */
    gap: 10px; /* 减少间距 */
    margin-bottom: 15px; /* 减少外边距 */
  }
  .header-section h2 {
    font-size: 1.8rem; /* 适当缩小标题字号 */
    font-weight: 700;
    color: #2c3e50;
    margin: 0;
    letter-spacing: 0.2px; /* 减少字母间距 */
  }
  .device-image {
    width: 100px; /* 进一步缩小图片大小 */
    height: 100px; /* 设置固定高度，与标题一致 */
    object-fit: cover; /* 保持图片比例 */
    border-radius: 10px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  }
  
  .input-section {
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 15px; /* 减少输入区域间距 */
  }
  
  .input-item-no-input {
    display: flex;
    align-items: center;
    gap: 8px; /* 减少钻石与标题间距 */
    flex-wrap: nowrap; /* 防止换行 */
    padding: 8px; /* 增加内边距 */
    border-radius: 8px; /* 增加圆角 */
  }
  .input-item-no-input h3,
  .input-item-no-input h4 {
    font-size: 1.1rem; /* 适当缩小次级标题字号 */
    font-weight: 600;
    color: #34495e;
    margin: 0;
    white-space: nowrap; /* 防止文字换行 */
  }
  .red-diamond {
    color: #e74c3c;
    font-size: 1.2rem; /* 适当缩小钻石字号 */
  }
  
  .input-group {
    display: flex;
    flex-direction: row; /* 改为水平排列 */
    align-items: center; /* 垂直居中对齐 */
    gap: 8px; /* 减少组内间距 */
    width: 100%;
  }
  .group-title {
    font-size: 1rem; /* 适当缩小组标题字号 */
    color: #3498db;
    font-weight: 500;
    margin-bottom: 0; /* 移除底部间距 */
    white-space: nowrap; /* 防止文字换行 */
    min-width: 80px; /* 设置最小宽度，保持对齐 */
  }
  .group-input {
    flex: 1; /* 让输入框占据剩余空间 */
  }
  
  /* 调整 Element Plus 输入框的默认样式以匹配整体主题 */
  :deep(.el-textarea__inner) {
    border-radius: 6px; /* 统一输入框圆角 */
    border: 1px solid #dcdfe6;
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.03); /* 内部阴影 */
    transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  }
  :deep(.el-textarea__inner:focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.2); /* 聚焦时外发光效果 */
  }
  
  .middle-image-container {
    grid-column: 1 / 3;
    grid-row: 1 / 3;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 15px; /* 减少间距 */
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 15px; /* 适当减少圆角 */
    padding: 20px; /* 减少内边距 */
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12); /* 调整阴影 */
    z-index: 1; /* 调整层级，使其在文字下方但可见 */
    position: absolute;
    top: 30%; /* 上移一段距离 */
    left: 50%;
    transform: translate(-50%, -50%);
    width: auto;
    height: auto;
    min-width: 250px; /* 缩小最小尺寸 */
    min-height: 250px;
    max-width: 300px; /* 增加最大宽度限制 */
    max-height: 300px; /* 增加最大高度限制 */
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  
  .middle-image-container h2 {
    font-size: 1.5rem; /* 缩小中心标题字号 */
    font-weight: 800;
    color: #2980b9;
    margin: 0;
    text-shadow: 1px 1px 2px rgba(0,0,0,0.08); /* 调整文本阴影 */
    text-align: center; /* 文字居中 */
  }
  
  .middle-image {
    width: 200px; /* 缩小中心图片大小 */
    height: auto;
    border-radius: 15px;
    box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
    margin-top: 10px; /* 增加与标题的间距 */
  }
  
  /* 响应式调整 */
  @media (max-width: 1200px) {
    .grid-container {
      grid-template-columns: 1fr; /* 小屏幕下堆叠显示 */
      gap: 20px;
      max-width: 90%;
    }
    .collect-card, .middle-image-container {
      grid-column: 1 / -1; /* 占据整列 */
      position: static; /* 移除绝对定位 */
      transform: none; /* 移除平移 */
      min-width: unset;
      min-height: unset;
      max-width: unset; /* 移除最大宽度限制 */
      max-height: unset; /* 移除最大高度限制 */
    }
    .middle-image-container {
      order: -1; /* 让中心图片在小屏幕上显示在顶部 */
      margin-bottom: 20px; /* 增加下方间距 */
    }
    .middle-image {
      width: 70%; /* 适应小屏幕 */
      max-width: 200px;
    }
    .header-section h2 {
      font-size: 1.5rem;
    }
    .input-item-no-input h3, .input-item-no-input h4 {
      font-size: 1rem;
    }
    .group-title {
      font-size: 0.95rem;
    }
    .collect-card {
      padding: 20px;
    }
  }
  
  @media (max-width: 768px) {
    .collect-root {
      padding: 15px;
    }
    .collect-card {
      padding: 18px;
      gap: 10px;
    }
    .header-section {
      margin-bottom: 10px;
    }
    .header-section h2 {
      font-size: 1.2rem;
    }
    .device-image {
      width: 80px;
    }
    .input-section {
      gap: 10px;
    }
    .input-item-no-input h3, .input-item-no-input h4 {
      font-size: 0.9rem;
    }
    .red-diamond {
      font-size: 1rem;
    }
    .group-title {
      font-size: 0.85rem;
    }
    .middle-image-container h2 {
      font-size: 1.2rem; /* 缩小中心标题字号 */
    }
    .middle-image {
      width: 60%;
      max-width: 180px;
    }
  }
  
  @media (max-width: 480px) {
    .collect-root {
      padding: 10px;
    }
    .collect-card {
      padding: 15px;
    }
    .header-section h2 {
      font-size: 1rem;
    }
    .device-image {
      width: 60px;
    }
    .input-item-no-input h3, .input-item-no-input h4 {
      font-size: 0.8rem;
    }
    .group-title {
      font-size: 0.8rem;
    }
    .middle-image-container h2 {
      font-size: 1rem; /* 缩小中心标题字号 */
    }
    .middle-image {
      width: 50%;
      max-width: 150px;
    }
  }
  </style>